package club.babyf.nativeai.functioncalling.functions;

import club.babyf.nativeai.functioncalling.exception.FunctionExecutionException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * AbstractFunction.
 *
 * @author zhanglei.
 * @date 2025/2/21 10:39.
 * @description 抽象函数.
 */
public abstract class AbstractFunction<T, R> implements Function<T, R> {

    private final Class<T> paramType;

    protected final ObjectMapper mapper = new ObjectMapper();

    protected AbstractFunction(Class<T> paramType) {
        this.paramType = paramType;
    }

    @Override
    public R execute(T parameters) {
        validateParams(parameters);
        return doExecute(parameters);
    }

    protected abstract R doExecute(T parameters);

    private void validateParams(T parameters) {
        if (parameters == null) {
            throw new FunctionExecutionException("INVALID_PARAMS", "Parameters cannot be null");
        }
    }

    public T parseParams(String json) throws FunctionExecutionException {
        try {
            return mapper.readValue(json, paramType);
        } catch (Exception e) {
            throw new FunctionExecutionException("INVALID_PARAMS", "Failed to parse parameters: " + e.getMessage());
        }
    }

    public Class<T> getParamType() {
        return paramType;
    }

}
